<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 顶部查询列表 -->
      <el-col :lg="24" :xs="24">
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="名称" prop="category">
              <el-input
                v-model="queryParams.category"
                placeholder="请输入名称"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
                @clear="handleQuery"
              />
            </el-form-item>
            <el-form-item label="时间" prop="add_date">
              <el-date-picker
                v-model="queryParams.add_date"
                type="daterange"
                placeholder="时间"
                unlink-panels
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                :shortcuts="shortcuts"
                :size="size"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery"
                ><i-ep-search />搜索</el-button
              >
              <el-button @click="handleResetQuery">
                <i-ep-refresh />
                重置</el-button
              >
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never" class="table-container">
          <template #header>
            <div class="flex justify-between">
              <div>
                <el-button type="success" @click="openDialog(DialogType.ADD)"
                  ><i-ep-plus />新增</el-button
                >
                <el-button
                  type="danger"
                  :disabled="removeIds.length === 0"
                  @click="handleDelete()"
                  ><i-ep-delete />批量删除</el-button
                >
              </div>
              <div>
                <el-dropdown split-button>
                  导入
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="downloadTemplate">
                        <i-ep-download />下载模板</el-dropdown-item
                      >
                      <el-dropdown-item @click="openDialog(DialogType.IMPORT)">
                        <i-ep-top />导入数据</el-dropdown-item
                      >
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
                <el-button class="ml-3" @click="handleExport"
                  ><template #icon><i-ep-download /></template>导出</el-button
                >
              </div>
            </div>
          </template>
          <!-- 展示表单 -->
          <el-table
            v-loading="loading"
            :data="pageData"
            border
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="60" align="center" />
            <el-table-column key="id" label="ID" align="center" width="60">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column
              label="日期"
              align="center"
              prop="add_date"
              width="160"
            />
            <!-- <el-table-column
              label="菜品类型"
              align="center"
              prop="type_order"
            /> -->
            <el-table-column label="菜品名称" align="center" prop="category" />
            <el-table-column
              label="批发价"
              align="center"
              prop="wholesale_price"
            />
            <el-table-column label="单价" align="center" prop="price" />
            <!-- <el-table-column label="备注" align="center" prop="remarks" /> -->
            <!-- <el-table-column
              label="创建时间"
              align="center"
              prop="CreatedTime"
              width="160"
            />
            <el-table-column
              label="更新时间"
              align="center"
              prop="UpdatedTime"
              width="160"
            /> -->
            <el-table-column
              label="操作"
              fixed="right"
              align="center"
              width="200"
            >
              <template #default="scope">
                <el-button
                  type="primary"
                  link
                  size="small"
                  @click="openDialog(DialogType.EDIT, scope.row)"
                  ><i-ep-edit />编辑</el-button
                >
                <el-button
                  type="primary"
                  link
                  size="small"
                  @click="handleDelete(scope.row.id)"
                  ><i-ep-delete />删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.page"
            v-model:limit="queryParams.pagesize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>
    <!-- echarts图表 -->
    <div ref="chart" style="width: 99%; height: 500px"></div>
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
    >
      <!-- 用户新增/编辑表单 -->
      <!-- <el-form
        v-if="isAddOrEdit || isDetail"
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="会员类型" prop="type_order">
          <el-input
            v-model="formData.type_order"
            autocomplete="off"
            placeholder="请输入会员类型"
            :disabled="isDetail"
          />
        </el-form-item>

        <el-form-item label="订单总价" prop="total_sales">
          <el-input
            v-model="formData.total_sales"
            autocomplete="off"
            placeholder="请输入订单总价"
            :disabled="isDetail"
          />
        </el-form-item>

        <el-form-item label="退款总额" prop="total_refund">
          <el-input
            v-model="formData.total_refund"
            autocomplete="off"
            placeholder="请输入退款总金额"
            :disabled="isDetail"
          />
        </el-form-item>
      </el-form> -->

      <!-- 用户导入表单 -->
      <!-- <el-form
        ref="userFormRef"
        v-else-if="isImport"
        :model="importData"
        label-width="100px"
      >
        <el-form-item label="Excel文件">
          <el-upload
            ref="uploadRef"
            action=""
            drag
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
            :limit="1"
            :auto-upload="false"
            :file-list="importData.fileList"
            :on-change="handleFileChange"
            :on-exceed="handleFileExceed"
          >
            <el-icon class="el-icon--upload">
              <i-ep-upload-filled />
            </el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <template #tip>
              <div>xls/xlsx files</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form> -->

      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="!isDetail" type="primary" @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
// import Abso_totalAPI from "@/api/abso/orderTotal";
import { ref, onMounted, PropType } from "vue";
import * as echarts from "echarts";
import { number } from "echarts";
import request from "@/utils/request";
import ProduceAPI from "@/api/abso/produce";
import {
  produceForm,
  produceQuery,
  produceTableVO,
  producePageVO,
} from "@/api/abso/produce/model";
import type { UploadInstance, TableColumnCtx } from "element-plus";
import { genFileId } from "element-plus";
import { DialogType } from "@/enums/DialogType";

const chart = ref<HTMLDivElement | null>(null);
const queryFormRef = ref(ElForm); // 查询表单
const userFormRef = ref(ElForm); // 用户表单
const uploadRef = ref<UploadInstance>(); // 上传组件
const loading = ref(false); //  加载状态
const removeIds = ref([]); // 删除用户ID集合 用于批量删除
const queryParams = reactive<PageQuery>({
  page: 1,
  pagesize: 10,
});
const dateTimeRange = ref("");
const total = ref(0); // 数据总数
const pageData = ref<produceTableVO[]>(); // 用户分页数据

//加载数据
const dataLoad = () => {
  request<any, ResponseData<producePageVO, produceTableVO[]>>({
    url: `produce/echart`,
    method: "get",
    params: { page: 1, pagesize: 100 },
  }).then((res) => {
    //请求失败的状况
    if (res.code != "200") {
      return;
    }
    if (chart.value) {
      //请求成功 开始绘制图表
      tableDraw(res.data);
    }
  });
};

const tableDraw = (data: producePageVO) => {
  if (chart.value) {
    const xAxisData = data.x;
    const seriesData: any[] = [];

    for (const vegetable in data) {
      if (vegetable !== "x") {
        seriesData.push({
          name: `${vegetable}`,
          type: "line",
          data: data[vegetable]?.price.map(Number),
        });
      }
    }

    const option = {
      backgroundColor: "#FFFFFF", // 设置背景色为白色
      title: {
        text: "",
      },
      tooltip: {
        trigger: "axis",
      },
      // tooltip: {
      //   trigger: "item", // 当鼠标悬停在数据点上时显示提示框
      //   formatter: (params: any) => {
      //     const vegetable = params.seriesName.split(" ")[0]; // 获取蔬菜名称
      //     const wholesalePrice =
      //       data[vegetable].wholesale_price[params.dataIndex]; // 获取批发价格
      //     return `${params.seriesName}: ${params.value} 元<br/>批发价格: ${wholesalePrice} 元`;
      //   },
      // },

      // tooltip: {
      //   trigger: 'axis', // 触发类型为坐标轴
      //   formatter: (params: any) => {
      //     const dateIndex = params[0].dataIndex; // 获取当前点的索引
      //     let tooltipContent = `${data.x[dateIndex]}<br/>`; // 显示日期

      //     params.forEach((item: any) => {
      //       const vegetable = item.seriesName.split(' ')[0]; // 获取蔬菜名称
      //       const price = item.value; // 获取价格
      //       // const wholesalePrice = data[vegetable].wholesale_price[dateIndex]; // 获取批发价格
      //       tooltipContent += `${vegetable} 价格: ${price} 元<br/>${vegetable} 批发价格: ${wholesalePrice} 元<br/>`;  //${vegetable} 批发价格: ${wholesalePrice} 元<br/>
      //     });

      //     return tooltipContent; // 返回拼接的内容
      //   },
      //   hideDelay: 0 // 鼠标移开后立即隐藏
      // },

      legend: {
        type: "scroll",
        orient: "horizontal", // 纵向，默认横向不用写
        pageIconColor: "#1b9aee", //翻页下一页的三角按钮颜色
        pageIconInactiveColor: "#7f7f7f", //翻页（即翻页到头时）
        // 配置滚动类型的图例
        pageTextStyle: {
          color: "#7f7f7f", // 可以根据需求调整样式
        },
        textStyle: {
          color: "#000",
          fontSize: 12,
        },
        top: 5,
        left: "20%",
        right: "20%",
        data: seriesData.map((s) => s.name) || [],
      },
      xAxis: {
        type: "category",
        data: xAxisData,
        boundaryGap: false,
      },
      yAxis: [
        {
          type: "value",
          name: "",
          position: "left",
          axisLabel: {
            formatter: "{value}元",
          },
        },

        // {
        //   type: "value",
        //   name: "批发价格",
        //   position: "right",
        //   axisLabel: {
        //     formatter: "{value} 元",
        //   },
        // },
      ],
      series: seriesData,
      dataZoom: [
        {
          type: "slider",
          xAxisIndex: [0],
          start: 0,
          end: 100,
        },
      ],
    };

    const myChart = echarts.init(chart.value);
    myChart.setOption(option);
  }
};

// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "number-form",
  width: 800,
  title: "",
});

// 用户表单数据
const formData = reactive<produceForm>({});

// 用户导入数据
const importData = reactive({
  // deptId: undefined,
  file: undefined,
  fileList: [],
});

// 校验规则
// const rules = reactive({
//   // username: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
//   // name: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
//   // password: [{ required: true, message: "密码不能为空", trigger: "blur" }],
//   // deptId: [{ required: true, message: "所属部门不能为空", trigger: "blur" }],
//   // roleIds: [{ required: true, message: "用户角色不能为空", trigger: "blur" }],
//   // email: [
//   //   {
//   //     pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
//   //     message: "请输入正确的邮箱地址",
//   //     trigger: "blur",
//   //   },
//   // ],
//   phone: [
//     {
//       pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
//       message: "请输入正确的手机号码",
//       trigger: "blur",
//     },
//   ],
// });

/** 查询 */
function handleQuery() {
  loading.value = true;
  ProduceAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.table;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function handleResetQuery() {
  queryFormRef.value.resetFields();
  dateTimeRange.value = "";
  queryParams.page = 1;
  handleQuery();
  dataLoad();
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

const isAddOrEdit = computed(() => {
  return dialog.type === DialogType.ADD || dialog.type === DialogType.EDIT;
});
const isDetail = computed(() => {
  return dialog.type === DialogType.DETAIL;
});

const isImport = computed(() => {
  return dialog.type === DialogType.IMPORT;
});

/**
 * 打开弹窗
 *
 * @param type 弹窗类型  用户表单：user-form | 用户导入：user-import
 * @param id 用户ID
 */
async function openDialog(
  type: string,
  row: {
    statu: any;
    id: any;
  }
) {
  dialog.visible = true;
  dialog.type = type;
  switch (dialog.type) {
    case DialogType.ADD:
      dialog.title = "新增表单";
      Object.assign(formData, {});
      break;
    case DialogType.EDIT:
      dialog.title = "修改表单";
      Object.assign(formData, { ...row, statu: String(row.statu) });
      break;
    case DialogType.IMPORT:
      // 用户导入弹窗
      dialog.title = "导入用户";
      dialog.width = 600;
      break;
    case DialogType.DETAIL:
      dialog.title = "查看详情";
      Object.assign(formData, { ...row, statu: String(row.statu) });
      break;

    default:
      break;
  }
}

/**
 * 关闭弹窗
 *
 * @param type 弹窗类型  用户表单：user-form | 用户导入：user-import
 */
function closeDialog() {
  dialog.visible = false;
  if (isAddOrEdit.value) {
    userFormRef.value.resetFields();
    userFormRef.value.clearValidate();

    // formData.id = 0;
    // formData.status = 1;
  } else if (isImport.value) {
    importData.file = undefined;
    importData.fileList = [];
  }
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  if (dialog.type === DialogType.IMPORT) {
    // TODO 导入逻辑
  } else if (
    dialog.type === DialogType.ADD ||
    dialog.type === DialogType.EDIT
  ) {
    userFormRef.value.validate((valid: any) => {
      if (valid) {
        const userId = formData.id;
        loading.value = true;
        if (userId) {
          ProduceAPI.update(userId, formData as any)
            .then(() => {
              ElMessage.success("修改成功");
              closeDialog();
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
        } else {
          // console.log(formData, "formData");

          ProduceAPI.add(formData)
            .then((res) => {
              // console.log(res, "res");

              ElMessage.success("新增成功");
              closeDialog();
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
        }
      }
    });
  }
}, 3000);

/** 删除用户 */
function handleDelete(id?: number) {
  const userIds = [id || removeIds.value].join(",");
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除用户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    ProduceAPI.deleteByIds(userIds).then(() => {
      ElMessage.success("删除成功");
      handleResetQuery();
    });
  });
}

onMounted(() => {
  handleQuery();
  dataLoad();
});
</script>
